package com.hotel.services.impl;

import com.hotel.daos.PermissionMapper;
import com.hotel.entitys.Permission;
import com.hotel.entitys.TreeNode;
import com.hotel.services.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    public List<Permission> selPerByUser(String telephone,Integer pid){
        return permissionMapper.selPerByUser(telephone,pid);
    }

    @Override
    public List<TreeNode> selAllPer(Integer pid) {
        List<TreeNode> tree = new ArrayList<TreeNode>();
        //查询到了所有的一级功能，因为pid的值是从控制器中带来的。
        List<Permission> onePer = permissionMapper.selAllPer(pid);
        for (Permission per:onePer){
            TreeNode treeNode = changeTree(per);
            tree.add(treeNode);
        }
        return tree;
    }

    public TreeNode changeTree(Permission permission){
        TreeNode treeNode = new TreeNode();
        treeNode.setId(permission.getPer_id());
        treeNode.setLabel(permission.getPer_name());
        List<Permission> childrenPer = permissionMapper.selAllPer(permission.getPer_id());
        if(!childrenPer.isEmpty()){
            List<TreeNode> treeChildren = new ArrayList<TreeNode>();
            for (Permission per:childrenPer){
                TreeNode treeNodeChildren = changeTree(per);
                treeChildren.add(treeNodeChildren);
            }
            treeNode.setChildren(treeChildren);
        }
        return treeNode;
    }

    @Override
    public List<Integer> selPerByRid(Integer rid) {
        return permissionMapper.selPerByRid(rid);
    }

    @Override
    public int delPerByRid(Integer rid) {
        return permissionMapper.delPerByRid(rid);
    }

    @Override
    public int addPerByRid(Integer rid, List<Integer> perids) {
        return permissionMapper.addPerByRid(rid,perids);
    }

    @Override
    public List<Integer> selPerBySid(String telephone) {
        return permissionMapper.selPerBySid(telephone);
    }
}
